"use strict";

var dappAddress = "n22Rfh9SLuU5P94LHTA954yBr2kZ9L9szgT";
var hash = "11eaa4b15059e1410d9f75b38806c9016cf17fe39f691e05fa4a32dfdda82ed3";
var NebPay = require("nebpay");
var nebPay = new NebPay();
var html = '';
var allScore = '';

if (typeof webExtensionWallet === "undefined") {
  layer.msg('星云钱包环境未运行，请安装钱包插件')
}

function dateTrans(longTypeDate){
  let date = new Date(longTypeDate);
  Date.prototype.format = function(f){
    var o ={
      "M+" : this.getMonth()+1, //month
      "d+" : this.getDate(),    //day
      "h+" : this.getHours(),   //hour
      "m+" : this.getMinutes(), //minute
      "s+" : this.getSeconds(), //second
      "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
      "S" : this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(f))f=f.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
      if(new RegExp("("+ k +")").test(f))f = f.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));return f
  };
  return date.format('yyyy-MM-dd hh:mm:ss');
}

nebPay.simulateCall(dappAddress, "0", "get", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          layer.msg('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var datalist = JSON.parse(res.result);
      console.log(datalist);
      renderSearch(datalist)
    }
})

function renderSearch (data) {
  var datas = JSON.parse(data);
  console.log(datas);

  if (datas && datas.length) {
    var datalist = datas.sort(function (a, b) {
      var value1 = a.step,
          value2 = b.step;
      if(value1 === value2){
          return a.date - b.date;
      }
      return value1 - value2;
    })

    allScore = datalist;
    
    for (var i = 0; i < datalist.length; i++) {
      if (i < 20) {
        html += `<tr><td>${i+1}</td><td>${datalist[i].username}</td><td>${datalist[i].step}</td><td>${dateTrans(datalist[i].date)}</td></tr>`
      }
    }
  } else {
    html += '<tr><td>暂无数据！</td></tr>'
  }
}


$('#ranking').click(function(){
  if(html){
    layer.open({
      type: 1,
      title: 'Top 20',
      skin: 'layui-layer-rim',
      area: ['420px', '240px'], //宽高
      content: `<div id='rankList'><table><tr><th>ranking</th><th>userName</th><th>step</th><th>time</th></tr>${html}</table></div>`
    });
  }else{
    layer.msg('loading...please try angin later!');
  }
})

$('#myScore').click(function(){
  var html = '';
  layer.prompt(function(val){
    for (var i = 0; i < allScore.length; i++) {
      if(allScore[i].username == val){
        html += `<tr><td>${i+1}</td><td>${allScore[i].username}</td>
          <td>${allScore[i].step}</td>
          <td>${dateTrans(allScore[i].date)}</td>
          </tr>`
      }
    }
    if(html){
       layer.open({
        type: 1,
        title: 'my score',
        skin: 'layui-layer-rim',
        area: ['420px', '240px'], //宽高
        content: `<div id='rankList'><table><tr><th>ranking</th><th>userName</th><th>step</th><th>time</th></tr>${html}</table></div>`
      });
    }   
  });
})